/*
 * Copyright 2011 myTDev.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mytdev.util.properties.formatters.impl;

import com.mytdev.util.properties.formatters.Formatter;
import com.mytdev.util.properties.formatters.FormatterProvider;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author Yann D'Isanto
 */
public final class EnumFormatterProvider implements FormatterProvider {

    /**
     * The formatters.
     */
    private final Map<Class<? extends Enum>, Formatter<? extends Enum>> formatters = new HashMap<Class<? extends Enum>, Formatter<? extends Enum>>();

    public EnumFormatterProvider() {
    }

    /**
     * Returns the formatter associated with the specified type. If no formatter
     * is associated with the specified type a default EnumFormatter is
     * returned.
     *
     * @param type the type.
     * @return a formatter instance.
     * @see EnumFormatter
     */
    @SuppressWarnings("unchecked")
    public <T> Formatter<T> getFormatter(Class<T> type) throws IllegalArgumentException {
        if (!Enum.class.isAssignableFrom(type)) {
            throw new IllegalArgumentException("Not an enum type: " + type.getName());
        }
        Formatter<T> formatter = (Formatter<T>) formatters.get(type);
        if (formatter == null) {
            formatter = new EnumFormatter(type);
            setFormatter(type, formatter);
        }
        return formatter;
    }

    /**
     * Associates the specified formatter with the specified type.
     *
     * @param type the type, must be not null.
     * @param formatter the formatter. Can be null.
     * @throws NullPointerException if type is null.
     * @throws IllegalArgumentException if type is not an enum type.
     */
    @SuppressWarnings("unchecked")
    public <T> void setFormatter(Class<T> type, Formatter<T> formatter) {
        if (!Enum.class.isAssignableFrom(type)) {
            throw new IllegalArgumentException("Not an enum type: " + type.getName());
        }
        formatters.put((Class<? extends Enum>) type, (Formatter<? extends Enum>) formatter);
    }
}
